/*
 * Copyright (c) 2012 Jonathan Tyers
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package uk.org.uplink.configproxy;

import static java.util.Arrays.asList;

import java.beans.Introspector;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.event.ConfigurationEvent;
import org.apache.commons.configuration.event.ConfigurationListener;

import uk.org.uplink.configproxy.exception.RequiredConfigurationKeyNotPresentException;
import uk.org.uplink.configproxy.validator.ConfigProxyValidator;
import uk.org.uplink.configproxy.validator.PatternConfigProxyValidator;
import uk.org.uplink.configproxy.validator.PatternSelector;

/**
 * Looks up values of {@link ConfigValue}s using a provided {@link HierarchicalConfiguration}. This class co-ordinates any conversion,
 * default keys/values and validation that takes place against returned values.
 * 
 * @author jonny
 */
public class ConfigValueResolver implements InvocationHandler, ConfigurationListener {
	public static final String getPrefix = "get";
	public static final String setPrefix = "set";
	public static final String isPrefix = "is";

	/**
	 * Write operations that affect single properties.
	 */
	private static final List<Integer> PROPERTY_OPERATIONS = asList(
			AbstractConfiguration.EVENT_ADD_PROPERTY,
			AbstractConfiguration.EVENT_CLEAR_PROPERTY,
			AbstractConfiguration.EVENT_SET_PROPERTY
			);

	private final HierarchicalConfigurationWrapper configuration;

	private final ConfigProxyValidator validator;

	private final ConvertUtilsBean convertUtilsBean;

	private final ConfigProxy configProxy;

	private final ConfigValueResolverCache resolverCache;

	/**
	 * Factory method to make it easy to create resolvers when a DI framework is not in use. This method will create a resolver that looks up values
	 * against the given configuration, with the validation and converter classes in use.
	 * 
	 * @param configuration the configuration to use to look up values
	 * @return
	 */
	public static ConfigValueResolver create(final Class<?> interfaze, final HierarchicalConfiguration configuration) {
		return new ConfigValueResolver(
				interfaze, new HierarchicalConfigurationWrapper(configuration),
				new PatternConfigProxyValidator(new PatternSelector()), new ConvertUtilsBean(), new ConfigValueResolverCache());
	}

	@Inject
	public ConfigValueResolver(final Class<?> interfaze, final HierarchicalConfigurationWrapper configuration,
			final ConfigProxyValidator validator, final ConvertUtilsBean convertUtilsBean, final ConfigValueResolverCache resolverCache) {
		super();
		this.configuration = configuration;
		this.validator = validator;
		this.convertUtilsBean = convertUtilsBean;
		this.resolverCache = resolverCache;

		configProxy = getConfigProxyAnnotation(interfaze);
		configuration.addConfigurationListener(this);
	}

	private Object getConfigurationValue(final MethodInfo methodInfo) {
		ConfigValue configValue = methodInfo.getConfigValue();
		String key = getCombinedKey(getConfigValueKey(methodInfo, configValue), configValue.absolute());

		Class<?> returnType = methodInfo.getReturnType();

		List<Option> options = asList(configValue.options());
		if (options.contains(Option.CHECK_KEY_EXISTS)) {
			if (returnType != Boolean.class && returnType != boolean.class) {
				throw new IllegalArgumentException(String.format("Method %s on %s must return a boolean, as it has the %s option set",
						methodInfo.getName(), methodInfo.getDeclaringClassName(), Option.CHECK_KEY_EXISTS.name()));
			}

			/* no need for other checks, so return straight away */
			return configuration.containsKeyRegardlessOfValue(key);
		}

		Object result = configuration.get(returnType, key, null);

		if (result == null) {
			if (options.contains(Option.REQUIRED)) {
				throw new RequiredConfigurationKeyNotPresentException(key);
			}
			result = getDefaultValue(methodInfo, configValue);
		}

		validator.validate(methodInfo, result);

		return result;
	}

	@Override
	public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
		ConfigValue configValue = method.getAnnotation(ConfigValue.class);
		if (configValue == null) {
			configValue = Defaults.getDefaultConfigValueAnnotation();
		}

		MethodInfo methodInfo = new MethodInfo(method.getDeclaringClass().getCanonicalName(), method.getName(), configValue,
				method.getReturnType());

		if (resolverCache.contains(methodInfo)) {
			return resolverCache.get(methodInfo);
		}

		Object result = getConfigurationValue(methodInfo);
		resolverCache.put(methodInfo, result);

		return result;
	}

	@Override
	public void configurationChanged(final ConfigurationEvent event) {
		int operationType = event.getType();

		if (PROPERTY_OPERATIONS.contains(operationType)) {
			String propertyName = event.getPropertyName();
			resolverCache.removeByConfigValueKey(propertyName);

		} else if (operationType == AbstractConfiguration.EVENT_CLEAR) {
			resolverCache.clear();
		}
	}

	private ConfigProxy getConfigProxyAnnotation(final Class<?> interfaze) {
		ConfigProxy configProxy = interfaze.getAnnotation(ConfigProxy.class);

		if (configProxy != null) {
			return configProxy;
		}
		return Defaults.getDefaultConfigProxyAnnotation();
	}

	/**
	 * @return the key of a config value, using the name of its method or underlying Javabean property name if necessary
	 */
	private String getConfigValueKey(final MethodInfo methodInfo, final ConfigValue configValue) {
		if (!configValue.key().equals("")) {
			return configValue.key();
		}

		String name = methodInfo.getName();

		// FIXME No need to verify argCount?
		//        int argCount = method.getParameterTypes().length;
		//        if (argCount == 0) {

		if (name.startsWith(getPrefix)) {
			return Introspector.decapitalize(name.substring(getPrefix.length()));
		}
		if (name.startsWith(isPrefix)) {
			return Introspector.decapitalize(name.substring(isPrefix.length()));
		}

		//        }
		return name; // default to the method name
	}

	private String getCombinedKey(final String partialKey, final boolean isAbsolute) {
		if (isAbsolute) {
			return partialKey;
		}

		String baseKey = configProxy.basekey();
		if (baseKey == null || baseKey.equals("")) {
			return partialKey;
		}

		if (baseKey.endsWith(".") || partialKey.startsWith(".")) {
			return baseKey + partialKey;
		}

		return baseKey + "." + partialKey;
	}

	private Object getDefaultValue(final MethodInfo methodInfo, final ConfigValue configValue) {
		String defaultKey = configValue.defaultKey();
		String defaultValue = configValue.defaultValue();
		Class<?> returnType = methodInfo.getReturnType();

		if (!defaultKey.isEmpty() && !defaultValue.isEmpty()) {
			throw new IllegalArgumentException(String.format(
					"The @ConfigValue annotation for method %s() on %s specifies both defaultKey and defaultValue", methodInfo.getName(),
					methodInfo.getDeclaringClassName()));
		}

		if (!defaultKey.isEmpty()) {
			String combinedDefaultKey = getCombinedKey(defaultKey, configValue.defaultKeyAbsolute());
			return configuration.get(returnType, combinedDefaultKey, null);

		} else if (!defaultValue.isEmpty()) {
			return convertUtilsBean.convert(defaultValue, returnType);

		} else {
			return null;
		}
	}
}
